import { BaseException, ServerException } from "@exceptions";

/**
 * 异常错误拦截装饰器
 * @param {string} desc 描述内容
 * @param {function} cacheCb
 */
export const CatchError = (desc?: string, cacheCb?: (e: any) => void) => {
    return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const fn = descriptor.value
        descriptor.value = async function (...args) {
            try {
                return await fn.apply(this, args)
            } catch (e) {
                cacheCb && cacheCb(e)
                // 自定义异常
                if (e instanceof BaseException) {
                    console.log(`CatchError::${desc}, Error：`, e.getMessage())
                    throw e
                } else {
                    console.log(`CatchError::${desc}, Error：`, e.message)
                    throw new ServerException(e)
                }
            }
        }
    }
}
